import axios from 'axios'
import { message } from 'antd'

const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
})
// if (import.meta.env.VITE_API_BASE_URL) {
//   axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL
// }

// 请求拦截器
service.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if (token) config.headers.Authorization = `Bearer ${token}`
  return config
})

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data
    // 处理响应数据
    if (res.code !== 200) {
      message.error({
        content: res.msg || 'Error',
        duration: 5 * 1000,
      })
      if (res.code === 10000) {
        window.location.href =
          import.meta.env.VITE_API_BASE_URL + '/htdocs/login.html'
      }

      return Promise.reject(new Error(res.msg || 'Error'))
    }
    return res
  },
  (error) => {
    message.error(error.response?.data?.msg || '请求失败')
    return Promise.reject(error)
  }
)

export default service
